// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const closetimeCollection = db.collection('closetime')
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let existState

  await closetimeCollection.where({
    openid: wxContext.OPENID
  }).get().then(res => {
    existState = res.data.length
  })

  if (existState == 0) {
    await closetimeCollection.add({
      data: {
        openid: wxContext.OPENID,
        closetime: new Date().getTime()
      }
    })
  } else {
    await closetimeCollection.where({
      openid: wxContext.OPENID
    }).update({
      data: {
        closetime: new Date().getTime()
      }
    })
  }
  return 1
}